package com.example.interceptor;

import com.example.config.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		// 1.通过request对象获取Session对象
		HttpSession session = request.getSession();



		//4、判断登录状态，如果已登录，则直接放行
		if(session.getAttribute("employee") != null){

			BaseContext.setCurrentId((Long) session.getAttribute("employee"));

			log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));
			return true;
		}

		log.info("用户未登录");

		//5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
//		response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
		response.sendRedirect("/backend/page/login/login.html");
		return false;
	}

	@Override
	public void afterCompletion(
			HttpServletRequest request,
			HttpServletResponse response,
			Object handler,
			Exception ex) throws Exception {
		BaseContext.remove();
	}

}
